<script lang="ts" setup>
import { nextTick, reactive, ref } from 'vue';

import { ElButton, ElDialog, ElMessage, ElTree } from 'element-plus';

import { getList } from '#/api/upms/menu';
import { getTenantMenuList, saveTenantMenu } from '#/api/upms/tenant';

interface State {
  menuList: Array<any>;
  menuIds: Array<string>;
  sysRole: any;
}
const emit = defineEmits(['initPage']);
const menuRef = ref();
const dialog = ref(false);
const tenantId = ref();
const state = reactive<State>({ menuList: [], menuIds: [], sysRole: {} });
const loading = ref(false);
const defaultProps = ref({
  children: 'children',
  label: 'name',
  disabled: 'disabled',
});
/**
 * 选择菜单权限事件
 */
const handleChange = () => {
  const checkedKeys = menuRef.value.getCheckedKeys(false);
  const halfCheckedKeys = menuRef.value.getHalfCheckedKeys(false);
  state.menuIds = [...checkedKeys, ...halfCheckedKeys];
};

/**
 * 获取指定角色的菜单
 */
const getTenantMenus = async (id: string) => {
  /**
   * 查询菜单树数据
   */
  await getList().then((response) => {
    state.menuList = response;
  });
  await getTenantMenuList(id).then((response) => {
    if (response) {
      state.menuIds = response.map((v) => v.menuId);
      if (state.menuIds) {
        state.menuIds.forEach((id: string) => {
          nextTick(() => {
            menuRef.value.setChecked(id, true, false);
          });
        });
      }
    }
  });
};
const onsubmit = () => {
  loading.value = true;
  saveTenantMenu({ menuIds: state.menuIds, tenantId: tenantId.value }).then(
    () => {
      loading.value = false;
      ElMessage.success('更新成功');
      dialog.value = false;
      emit('initPage');
    },
  );
};
const initMenu = (id: string) => {
  dialog.value = true;
  tenantId.value = id;
  getTenantMenus(id);
};
defineExpose({
  initMenu,
});
</script>
<template>
  <ElDialog
    v-model="dialog"
    title="分配菜单"
    width="50%"
    destroy-on-close
    v-loading="loading"
  >
    <ElTree
      ref="menuRef"
      :data="state.menuList"
      :props="defaultProps"
      node-key="id"
      show-checkbox
      @check="handleChange"
    >
      <template #default="{ node }">
        <span class="custom-tree-node">
          <span>{{ $t(node.label) }}</span>
        </span>
      </template>
    </ElTree>
    <template #footer>
      <span class="dialog-footer">
        <ElButton @click="dialog = false">取 消</ElButton>
        <ElButton type="primary" @click="onsubmit">确 认</ElButton>
      </span>
    </template>
  </ElDialog>
</template>
<style>
.hx-menus {
  width: 100%;
  height: 500px;
  padding: 4px;
  overflow-y: auto;
  border: 1px solid #dcdee0;
  border-radius: 4px;
}
</style>
